package com.wangy.service.impl;

import com.wangy.bean.Permission;
import com.wangy.mapper.PermissionMapper;
import com.wangy.mapper.RolePermissionMapper;
import com.wangy.service.RolePermissionService;
import com.wangy.util.PermissionHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author yyzb
 * @date 2024/12/28 20:09
 */
@Service
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    @Autowired
    PermissionMapper permissionMapper;

    // 把所有权限和角色拥有的权限id拿出来，如果角色拥有这个权限id那么select选项就设为是true
    // 最后构建树形结构
    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        List<Long> permissionsByRoleId = rolePermissionMapper.getPermissionsByRoleId(roleId);
        List<Permission> allPermissions = permissionMapper.getAllPermissions();
        ArrayList<Permission> permissionArrayList = new ArrayList<>();
        for(Permission permission: allPermissions){
            Permission item = new Permission();
            item.setId(permission.getId());
            item.setParentId(permission.getParentId());
            item.setPermissionName(permission.getPermissionName());
            item.setPermissionCode(permission.getPermissionCode());

            if (permissionsByRoleId.contains(permission.getId())){
                item.setSelect(true);
            }
            permissionArrayList.add(item);
        }
        ArrayList<Permission> buildTree = PermissionHelper.build(permissionArrayList);
        return buildTree;
    }

    /**
     * 先删除roleId所有权限，再添加permissionIds
     * @param roleId
     * @param permissionIds
     */
    @Override
    public void addRolePermissions(Long roleId, List<Long> permissionIds) {
        rolePermissionMapper.deleteByRoleId(roleId);
        rolePermissionMapper.addRolePermissions(roleId, permissionIds);
    }
}
